﻿using AutoMapper;
using MediatR;
using MonentExam1013.Api.Write.Appliaction.Commond;
using MonentExam1013.Domain;
using MonentExam1013.ErrorCode;
using MonentExam1013.infrastrunceture;
using System.Data;

namespace MonentExam1013.Api.Write.Appliaction.Commondhandler
{
    public class PermissionAddCommondHandler:IRequestHandler<PermissionAddCommond,ApiResult<int>>
    {
        private readonly IBaseIrepository<Permission> permission;
        private readonly IMapper mapper;

        public PermissionAddCommondHandler(IBaseIrepository<Permission> permission, IMapper mapper)
        {
            this.permission = permission;
            this.mapper = mapper;
        }

        public async Task<ApiResult<int>> Handle(PermissionAddCommond request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();
            result.Code = ApiEnum.增加成功;
            result.Msg = ApiEnum.增加成功.ToString();
            using(var tran= permission.Context.Database.BeginTransaction())
            {
                try
                {
                    Permission Permissions = mapper.Map<Permission>(request);
                    await permission.Add(Permissions);
                    tran.Commit();
                    return await Task.FromResult(result);
                }
                catch (Exception)
                {
                    tran.Rollback();
                    throw;
                }
            }
           
        }
    }
}
